# -*- encoding: utf-8 -*-
"""
-文件：server.py
-说明：服务端
-作者：tlj
"""
from socketserver import ThreadingTCPServer, StreamRequestHandler
from message import *
from block_chain.blockchain import BlockChain


class BlockchainHandler(StreamRequestHandler):
    """链接处理"""
    def handle(self):
        msg = BcMsg('').recv_msg(self.request)
        msg.handler(self.server)


class Server(ThreadingTCPServer):
    """
    服务端
    """
    CENTRAL_NODE = 'localhost:3000'  # 中心节点

    def __init__(self, node_id, miner_address_str):
        self.blockchain = BlockChain(node_id)  # 节点的区块链
        self.node_address = 'localhost:{}'.format(node_id)  # 节点地址
        self.known_nodes = [Server.CENTRAL_NODE]  # 与本节点建立连接的节点地址
        self.blocks_in_transit = []  # 本节点需要从其他节点获取的区块列表
        self.mempool = {}  # 本节点的交易池
        self.miner_address_str = miner_address_str

        host, port = self.node_address.split(':')
        port = int(port)
        super().__init__((host, port), BlockchainHandler)

        if self.node_address!= Server.CENTRAL_NODE:  # 与中心节点同步握手信息
            BcMsg('version', self.node_address,
                  self.blockchain.get_best_height()).send_msg(Server.CENTRAL_NODE)

    def run(self):
        """监听TCP服务请求"""
        print('Node{} is running...'.format(self.node_address))
        self.serve_forever()




